package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.JsonObject;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.LatitudeAndLongitude;
import com.sky.utils.getLngAndLat;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        //1 判断地址是否为空，若存在是否超出配送范围5km
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //超出配送范围
        LatitudeAndLongitude latAndLng = getLngAndLat.getLngAndLat("上海市浦东新区航都路18号");
        LatitudeAndLongitude latAndLng2 = getLngAndLat.getLngAndLat(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        double distance = getLngAndLat.getDistance
                (latAndLng.getLongitude(), latAndLng.getLatitude(), latAndLng2.getLongitude(), latAndLng2.getLatitude());
        System.out.println(distance);
        System.out.println("经度：" + latAndLng.getLongitude() + "---纬度：" + latAndLng.getLatitude());
        System.out.println("经度：" + latAndLng2.getLongitude() + "---纬度：" + latAndLng2.getLatitude());

        if(distance>5){
            throw new AddressBookBusinessException(MessageConstant.OUT_OF_DELIVERY_RANGE);
        }

        //2 判断购物车是否为空，用条件查询list
        ShoppingCart shoppingCart = ShoppingCart.builder().userId(BaseContext.getCurrentId()).build();
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (list == null || list.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //3 补全订单属性
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setUserId(BaseContext.getCurrentId()); //下单用户id
        order.setOrderTime(LocalDateTime.now()); //下单时间
        order.setPhone(addressBook.getPhone()); //电话
        order.setAddress(addressBook.getDetail()); //地址
        order.setNumber(String.valueOf(System.currentTimeMillis())); //订单号
        order.setConsignee(addressBook.getConsignee()); // 收货人
        order.setStatus(Orders.PENDING_PAYMENT); //状态：待付款
        order.setPayStatus(Orders.UN_PAID); //支付状态：未支付
        //4 插入订单表
        orderMapper.insert(order);
        //5 补全订单明细数据
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetails.add(orderDetail);
        }

        //6 插入订单明细表
        orderDetailMapper.insert(orderDetails);
        //7 清空购物车
        shoppingCartMapper.clean(BaseContext.getCurrentId());
        //8 封装返回结果
        return OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime()).build();
    }


    /**
     * 根据订单id查询订单
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO findById(Long id) {
        Orders orders = orderMapper.findById(id); //根据订单id 查orders表
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //根据orderId查询详情
        List<OrderDetail> orderDetails = orderDetailMapper.findByOrderId(id);
        return new OrderVO(JSONObject.toJSONString(orders), orderDetails);
    }

    /**
     * 历史订单分页查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.pageQuery(ordersPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());

    }

    /**
     * 根据id取消订单
     *
     * @param id
     */
    @Override
    public void cancelById(Long id) {
        //判断订单状态是否是已派出
        Orders orders = orderMapper.findById(id);
        if (orders.getStatus() > 3) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //order改属性，然后再表中update
        orders.setStatus(6);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     *
     * @param id 原来订单id
     */
    @Override
    public void repete(Long id) {
        List<OrderDetail> list = orderDetailMapper.findByOrderId(id);

        Orders order = orderMapper.findById(id);
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(LocalDateTime.now());
        order.setStatus(2);
        order.setId(0L);
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        orderMapper.insert(order); //先以0插入 自增后再获取新的订单id insert返回主键id
        for (OrderDetail detail : list) {
            detail.setId(0L);
            detail.setOrderId(order.getId());
        }
        orderDetailMapper.insert(list);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO getStatistics() {
        //计算待接单数量
        Integer toBeConfirmed = orderMapper.countByStatus(2);
        //计算待派送数量
        Integer confirmed = orderMapper.countByStatus(3);
        //计算派送中数量
        Integer deliveryInProgress = orderMapper.countByStatus(4);
        return new OrderStatisticsVO(toBeConfirmed, confirmed, deliveryInProgress);
    }

    /**
     * 商家接单
     *
     * @param ordersDTO
     */
    @Override
    public void confirm(OrdersDTO ordersDTO) {
        String number = ordersDTO.getNumber();
        Orders order = orderMapper.getByNumber(number);
        order.setStatus(3);
        orderMapper.update(order);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void reject(OrdersRejectionDTO ordersRejectionDTO) {
        Orders order = orderMapper.findById(ordersRejectionDTO.getId());
        order.setStatus(6);
        orderMapper.update(order);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders order = orderMapper.findById(id);
        order.setStatus(4);
        order.setDeliveryStatus(1);
        orderMapper.update(order);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void conplete(Long id) {
        Orders order = orderMapper.findById(id);
        order.setStatus(5);
        order.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(order);
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);


        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 用户催单
     *
     * @param id
     */
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

}
